﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyWebPagesStarterKit;
using System.Reflection;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Web.Caching;
using MyWebPagesStarterKit.Controls;

public partial class Administration_Import : PageBaseClass
{

    private WebPage page;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            CreateList();
            populateList(SiteMap.RootNode,0);
            lstPages.Items.Insert(0,new ListItem("-----------------",""));
        }
    }

    private void CreateList()
    {
        List<ISection> sectionList = new List<ISection>();
        foreach (Type t in WebPage.Current.GetType().Assembly.GetTypes())
        {
            //find all classes that implement ISection and are not abstract
            if (t.IsClass && (t.GetInterface("ISection") != null) && (!t.IsAbstract))
            {
                //create a empty section-object for each found type
                ISection section = t.GetConstructor(new Type[] { }).Invoke(new object[] { }) as ISection;
                sectionList.Add(section);
            }
        }

        //sort the list alphabetically by their localized names
        sectionList.Sort(new Comparison<ISection>(sectionComparer));

        foreach (ISection section in sectionList)
        {
            cmbSections.Items.Add(new ListItem(section.GetLocalizedSectionName(), section.GetType().AssemblyQualifiedName));
        }
    }

    private void populateList(SiteMapNode parentNode, int level)
    {
        foreach (SiteMapNode node in parentNode.ChildNodes)
        {
            if (node["pageId"] != null)
            {
                string title = node.Title;
                for (int i = 0; i < level; i++)
                    title = "..." + title;
                if (node["visible"] == false.ToString())
                    title += " (invisible)";
                if (node["pageId"] == WebSite.GetInstance().HomepageId)
                    title += " (Homepage)";

                lstPages.Items.Add(new ListItem(title, node["pageId"]));
                populateList(node, level + 1);
            }
        }
    }


    /// <summary>
    /// Loads all templates or this webpage
    /// </summary>
    private void LoadTemplateList(WebPage page)
    {
        XmlDocument xml = new XmlDocument();
        xml.Load(Server.MapPath("~/web.config"));
        XmlNode root = xml.SelectSingleNode("configuration/templates/themes");
        lstPositions.Items.Clear();
        string theme = WebSite.GetInstance().Theme;

        if (root.HasChildNodes)
        {
            foreach (XmlNode node in root.ChildNodes)
            {
                if (page.TemplateName.Equals(node.Attributes["template"].Value))
                {
                    string[] columns = node.Attributes["columns"].Value.Split(new char[] { ',' });

                    foreach (string column in columns)
                    {
                        string name = string.Format("pos_{0}_Title", column.ToUpper());
                        lstPositions.Items.Add(new ListItem(Resources.StringsRes.ResourceManager.GetString(name), column));
                    }

                    break;
                }
            }
        }

    }
    protected void SetPage(object sender, EventArgs e)
    {
        page = new WebPage(lstPages.SelectedValue);
        LoadTemplateList(page);
    }

    private void InsertFile()
    {
        page = new WebPage(lstPages.SelectedValue);
       
    }

    private static int sectionComparer(ISection a, ISection b)
    {
        return a.GetLocalizedSectionName().CompareTo(b.GetLocalizedSectionName());
    }

   

    protected void Process(object sender, EventArgs e)
    {
        if (fileupload.HasFile && lstPages.SelectedIndex>0)
        {
            HttpPostedFile myFile = fileupload.PostedFile;

            int nFileLen = myFile.ContentLength;
            byte[] myData = new byte[nFileLen];
            myFile.InputStream.Read(myData, 0, nFileLen);

            FileStream fStream = new FileStream(myFile.FileName, FileMode.Open, FileAccess.Read);
            StreamReader sReader = new StreamReader(fStream);
            txtXml.Text = sReader.ReadToEnd();
          
            litErr.Text = "Succesfully read...<br/>";
            
            string[] types = cmbSections.SelectedValue.Split(new char[]{','});
            string[] typeName = types[0].Split(new char[] { '.' });
            string sectionName = typeName[1];
            string guid = Guid.NewGuid().ToString();
            string fileName = string.Format("~/App_Data/{0}/{1}.config", sectionName, guid);
            string path = Server.MapPath(fileName);

            string id = myFile.FileName.Substring(myFile.FileName.LastIndexOf("\\") + 1).Replace(".config", "");
            litErr.Text += "Created file: " + fileName;

            if (!Directory.Exists(Server.MapPath(string.Format("~/App_Data/{0}", sectionName))))
                Directory.CreateDirectory(Server.MapPath(string.Format("~/App_Data/{0}", sectionName)));

            using (FileStream writer = File.Create(path))
                writer.Write(myData, 0, myData.Length);

            WebPage page = new WebPage(lstPages.SelectedValue);
            ISection section = (ISection)SectionLoader.GetInstance().LoadSection(guid);

            if (section == null)
                throw new Exception("This is not a valid section. Could not load type " + sectionName + ".");
       
            Position pos = Position.UNKNOWN;
            switch (lstPositions.SelectedValue)
            {
                case "TOP":
                    pos = Position.TOP;
                    break;
                case "LEFT":
                    pos = Position.LEFT;
                    break;
                case "CENTER":
                    pos = Position.CENTER;
                    break;
                case "RIGHT":
                    pos = Position.RIGHT;
                    break;
                case "BOTTOM":
                    pos = Position.BOTTOM;
                    break;
            }

            if (section.Position == Position.UNKNOWN)
                throw new Exception("Section does not contain Position. Maybe this is an old section. Try update it before import.");

            section.Position = pos;
            section.SaveData();

            RolesManagement.GetInstance().AddRole(section, "UnAuthenticated", Rule.VIEW);
            RolesManagement.GetInstance().AddRole(section, "Users", Rule.VIEW);
            RolesManagement.GetInstance().AddRole(section, "PowerUsers", Rule.EDIT);

            page.AddSection(section.SectionId);
            page.SaveData();
               
            }
        }
}
